import time
import sys
import json
sys.path.append(r'.')
from DrissionPage import ChromiumPage


def load_param_datas_from_file(file_path):
    with open(file_path, "r", encoding='utf-8') as f:
        json_file_datas = json.loads(f.read())    # load的传入参数为字符串类型
        return json_file_datas


def select_words(table_div,page,savePath,words):
    # <button 屏蔽词设置</button>
    pingbi_button = table_div.ele('tag:button@@text():流量智选报告')
    # 计划没有执行
    if not pingbi_button:
        return
    pingbi_button.click()
    time.sleep(1)
    # 潜力词
    jinzhun_span_left = page.ele('tag:span@@text()^潜力词发现')
    if not jinzhun_span_left:
        return
    # 按钮区
    hidden_buttons_div = jinzhun_span_left.parent().next()
    # 批量屏蔽
    hidden_button = hidden_buttons_div.ele('tag:button@@text():批量屏蔽')

    # table表格div
    pb_table_div = hidden_buttons_div.next()

    pb_tbody_tag = pb_table_div.ele('tag:tbody')
    pb_trs = pb_tbody_tag.eles('tag:tr')
    if not pb_trs :
        return

    check_count = 0
    for pb_tr in pb_trs:
        pd_tds = pb_tr.eles('tag:td')
        if pd_tds and len(pd_tds) >= 2:
            checked_td = pd_tds[0]
            keyword_td = pd_tds[1]
            td_input = checked_td.ele('tag:input')
            keywords = keyword_td.texts()
            if len(keywords) > 0:
                for tag in words:
                    if keywords[0] == tag:
                        td_input.check()
                        check_count = check_count+1



    if check_count > 0:
        hidden_button.click()
    time.sleep(1)
    pb_table_div2 = hidden_buttons_div.next()
    # 保存table.html代码 到html文件中 (此时已经包含被屏蔽代码)
    with open(savePath, "w", encoding='utf-8') as file:
        file.write(pb_table_div2.html)

def item_block_words():
    json_file_datas = load_param_datas_from_file('item_block_words.data.json')
    port = json_file_datas['port']
    url = json_file_datas['url']
    words = json_file_datas['words']
    savePath = json_file_datas['savePath']
    page = ChromiumPage(addr_or_opts= '127.0.0.1:' + str(port))
    page.get(url)
    # 等待页面加载
    page.wait.load_start()
    # 滚动到最底部
    page.scroll.to_bottom()
    time.sleep(1)
    # 滚动到某个已获取到的元素

    add_keys_button = page.ele('tag:button@@text():添加关键词')
    table_div = add_keys_button.parent(4).next()
    tbody_tag = table_div.ele('tag:tbody')


    tbody_trs = tbody_tag.children()
    if tbody_trs and len(tbody_trs) > 0:
        for body_tr in tbody_trs:
            tr_tds = body_tr.children()
            if tr_tds and len(tr_tds) > 3:
                if '流量智选' == tr_tds[3].text:
                    body_tr.hover()  # 在元素上悬停鼠标
                    time.sleep(1)
                    select_words(table_div,page,savePath,words)








item_block_words()



